package com.nsgf.library.ui.page.home;

import static com.nsgf.library.data.api.APIs.H5_DUTY_RECORD;
import static com.nsgf.library.data.api.APIs.H5_INTRODUCE;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WeatherDetailBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.bean.XBannerBeanInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.DialogHomeUserSignDataBinding;
import com.nsgf.library.databinding.FragmentNsgfHomeBinding;
import com.nsgf.library.databinding.ItemTextBinding;
import com.nsgf.library.databinding.LayoutSpinnerPopupBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.photopicker.PhotoPreview;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.ui.adapter.HomeLabelGateListAdapter;
import com.nsgf.library.ui.adapter.HomeLabelGateTitleListAdapter;
import com.nsgf.library.ui.adapter.HomeLabelListAdapter;
import com.nsgf.library.ui.adapter.SimpleDataBindingPositionAdapter;
import com.nsgf.library.ui.adapter.ViewHolder;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.FloodSituationBriefingActivity;
import com.nsgf.library.ui.page.MaintenanceActivity;
import com.nsgf.library.ui.page.MessageActivity;
import com.nsgf.library.ui.page.MessageWarningActivity;
import com.nsgf.library.ui.page.ProjectOverviewActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.TaskPlanActivity;
import com.nsgf.library.ui.page.WebViewActivity;
import com.nsgf.library.ui.page.WebViewIntroduceActivity;
import com.nsgf.library.ui.page.manager.ManagerWorkOrderDetailsActivity;
import com.nsgf.library.ui.page.manager.WorkCreateActivity;
import com.nsgf.library.ui.page.manager.WorkOrderAlreadyActivity;
import com.nsgf.library.ui.page.manager.WorkOrderExamineAlreadyActivity;
import com.nsgf.library.ui.page.video.VideoListActivity;
import com.nsgf.library.utils.SPUtil;
import com.nsgf.library.utils.SpKey;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.utils.Utils;
import com.stx.xhb.xbanner.XBanner;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class HomeFragment extends BaseFragment {

    private HomeFragmentStates mStates;

    private FragmentNsgfHomeBinding mBinding;

    private HomeLabelListAdapter mAdapter;
    private HomeLabelGateListAdapter mAdapterGate;
    private HomeLabelGateTitleListAdapter mAdapterGateTitle;
    private List<LibraryInfo> mDatas = new ArrayList<>();

    private AccountRequester mAccountRequester;
    DialogHomeUserSignDataBinding binding;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(HomeFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    /**
     * 大坝巡查
     */
    public static final String DBXC = "patrol.type1";
    /**
     * 经常检查
     */
    public static final String JCJC = "patrol.type2";

    private String patrolType;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new HomeLabelListAdapter(getContext());

        mAdapterGateTitle = new HomeLabelGateTitleListAdapter(getActivity());

        mAdapterGateTitle.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<LibraryInfo>() {
            @Override
            public void onItemClick(int viewId, LibraryInfo item, int position) {
                for (LibraryInfo info :
                        mStates.listGateTitle.get()) {
                    info.setCheck(false);
                }
                item.setCheck(true);

                mAccountRequester.realTimeWorkConditions(UserInfo.getInstance().getProjectCode(), "device.gate.type." + (position + 1));
                mAdapterGateTitle.notifyDataSetChanged();
            }
        });

        mAdapter.setOnItemClickListener((viewId, item, position) -> {
            Intent intent;
            EventMsg eventMsg = new EventMsg();
            switch (position) {
                case 0:
                    patrolType = DBXC;
                    mAccountRequester.sameDayPatrolTask(DBXC);
                    break;
                case 1:
                    patrolType = JCJC;
                    mAccountRequester.sameDayPatrolTask(JCJC);
                    break;
                case 6:
                    eventMsg.setMsg("2");
                    EventBus.getDefault().post(eventMsg);
                    break;
                case 2:

                    intent = new Intent(getActivity(), ProjectOverviewActivity.class);
//                    intent.putExtra("url", H5_INTRODUCE);
                    intent.putExtra("title", "工程概况");
                    startActivity(intent);
                    break;
                case 3:
                    intent = new Intent(getActivity(), VideoListActivity.class);
                    startActivity(intent);
                    break;
                case 4:
                    intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("url", H5_DUTY_RECORD);
                    intent.putExtra("title", "值班管理");
                    startActivity(intent);
                    break;
                case 5:
                    intent = new Intent(getActivity(), TaskPlanActivity.class);
                    intent.putExtra("url", H5_DUTY_RECORD);
                    intent.putExtra("title", "任务计划");
                    startActivity(intent);
                    break;
                case 7:
                    intent = new Intent(getActivity(), MessageWarningActivity.class);
                    startActivity(intent);
                    break;
                case 8:
                    intent = new Intent(getActivity(), MessageActivity.class);
                    startActivity(intent);
                    break;
                case 9:
                    showDialog = true;
                    mAccountRequester.sameDayClockInDetail(UserInfo.getInstance().getProjectCode());
                    break;

                case 10:
                    intent = new Intent(getActivity(), WorkCreateActivity.class);
                    intent.putExtra("index",0);//险情上报
                    startActivity(intent);

                    break;

                case 11:
                    intent = new Intent(getActivity(), WorkCreateActivity.class);
                    intent.putExtra("index",1);//违法上报
                    startActivity(intent);
                    break;
                case 12:
                    intent = new Intent(getActivity(), FloodSituationBriefingActivity.class);
                    startActivity(intent);
                    break;
                case 13:
                    intent = new Intent(getActivity(), MaintenanceActivity.class);
                    startActivity(intent);
                    break;
            }
        });
        mAdapterGate = new HomeLabelGateListAdapter(getContext());
        return new DataBindingConfig(R.layout.fragment_nsgf_home, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.adapterGateTitle, mAdapterGateTitle)
                .addBindingParam(BR.adapterGate, mAdapterGate);
    }

    private List<XBannerBeanInfo> banners = new ArrayList<>();

    private List<Fragment> fragmentList = new ArrayList<>();

    private String[] mPageTitleList;

    @Override
    public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);

        mDatas.add(new LibraryInfo("大坝巡查", "", "", R.drawable.ic_nsgf_home_label_inspection));
        mDatas.add(new LibraryInfo("经常检查", "", "", R.drawable.ic_nsgf_home_label_test));
        mDatas.add(new LibraryInfo("工程概况", "", "", R.drawable.ic_nsgf_home_label_info));
        mDatas.add(new LibraryInfo("视频监控", "", "", R.drawable.ic_nsgf_home_label_video));
        mDatas.add(new LibraryInfo("值班管理", "", "", R.drawable.ic_nsgf_home_label_job));
        mDatas.add(new LibraryInfo("任务计划", "", "", R.drawable.ic_nsgf_home_label_task));
        mDatas.add(new LibraryInfo("我的待办", "", "", R.drawable.ic_nsgf_home_label_work));
        mDatas.add(new LibraryInfo("告警信息", "", "", R.drawable.ic_nsgf_home_label_warning));
        mDatas.add(new LibraryInfo("消息推送", "", "", R.drawable.ic_nsgf_home_label_message));
        mDatas.add(new LibraryInfo("考勤打卡", "", "", R.drawable.ic_nsgf_home_label_sign_in));
        mDatas.add(new LibraryInfo("险情上报", "", "", R.drawable.ic_home_label_dangerous));
        mDatas.add(new LibraryInfo("违法上报", "", "", R.drawable.ic_home_label_break));
        mDatas.add(new LibraryInfo("汛情简报", "", "", R.drawable.ic_home_label_briefing));
        mDatas.add(new LibraryInfo("维修养护", "", "", R.drawable.ic_home_label_repair));


        mStates.list.set(mDatas);
        mAdapter.notifyDataSetChanged();

        mBinding = (FragmentNsgfHomeBinding) getBinding();

        //打卡
        mAccountRequester.getSrc().observe(getViewLifecycleOwner(), dataResult -> {

            if (dataResult.getResponseStatus().isSuccess()) {
                if (200 == dataResult.getResult().getResponseCode()) {
                    ToastUtils.showLongToast("打卡成功");
                    dialog.dismiss();
                    mAccountRequester.sameDayClockInDetail(UserInfo.getInstance().getProjectCode());
                } else {
                    if (401 == dataResult.getResult().getResponseCode()) {
                        UserInfo.getInstance().clearUserInfo();
                    }
                    ToastUtils.showLongToast(dataResult.getResult().getMsg());
                }
            } else {
                ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
            }
        });

        // 获取水库信息
        mAccountRequester.reservoirInfo(UserInfo.getInstance().getProjectCode());
        mAccountRequester.getReservoirResult().observe(this, dataResult -> {


            if (dataResult.getResponseCode() == 200) {

                if (!StringUtil.isEmpty(dataResult.getData().getArea())) {

                    String[] area = dataResult.getData().getArea().split(",");
                    UserInfo.getInstance().setProjectLat(area[1]);
                    UserInfo.getInstance().setProjectLon(area[0]);
                }
                banners.clear();
                if (null != dataResult.getData().getFiles()) {
                    for (WorkOrderDetailBean.FileDto fileDto : dataResult.getData().getFiles()) {
                        banners.add(new XBannerBeanInfo(APIs.BASE_URL_IMG + fileDto.getFilePath()));
                    }
                    mBinding.xbanner.setBannerData(banners);
                    mBinding.xbanner.loadImage((banner, model, view, position) -> {
                        String url = (String) ((XBannerBeanInfo) model).getXBannerUrl();
                        GlideImgManager.getInstance().glideLoaderBannerCenterCrop(getActivity(),
                                url.replace("\\", "/"), (ImageView) view, 10);

                    });
                    mBinding.xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                        @Override
                        public void onItemClick(XBanner banner, Object model, View view, int position) {
                            ArrayList<WorkOrderDetailBean.FileDto> fileDtos = new ArrayList<>();
                            WorkOrderDetailBean.FileDto fileDto = new WorkOrderDetailBean.FileDto();
                            fileDto.setFilePath(banners.get(position).getXBannerUrl().toString());
                            fileDtos.add(fileDto);
                            PhotoPreview.builder()
                                    .setPhotos(fileDtos)
                                    .setAction(MultiPickResultView.ACTION_ONLY_SHOW)
                                    .start(getActivity());
                        }
                    });
                }
                mAccountRequester.getStatistics(UserInfo.getInstance().getProjectCode());

            } else {

                if (401 == dataResult.getResponseCode()) {
                    UserInfo.getInstance().clearUserInfo();
                    getActivity().finish();
                }
            }
        });
        List<LibraryInfo> list = new ArrayList<>();
        list.add(new LibraryInfo("溢洪闸", "", ""));
        list.add(new LibraryInfo("涵洞", "", ""));
        mStates.listGateTitle.set(list);
        mStates.listGateTitle.get().get(0).setCheck(true);
        mAdapterGateTitle.notifyDataSetChanged();

        mAccountRequester.realTimeWorkConditions(UserInfo.getInstance().getProjectCode(), "device.gate.type.1");
        mAccountRequester.getLibraryList().observe(this, new Observer<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onChanged(ResponseStatus<List<LibraryInfo>> dataResult) {

                if (dataResult.getResponseCode() == 200) {

                    if (null != dataResult.getData()) {
                        if (dataResult.getData().size() > 0) {

                            mStates.listGate.set(dataResult.getData());

                            mBinding.notdata.setVisibility(View.GONE);
                        } else {
                            mStates.listGate.set(new ArrayList<>());
                            mBinding.notdata.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    ToastUtils.showLongToast(dataResult.getMsg());
                }
            }
        });


        //获取消息统计
        mAccountRequester.getStatisticsResult().observe(this, dataResult -> {

            mBinding.swipeRefreshLayout.setRefreshing(false);
            if (dataResult.getResponseStatus().isSuccess()) {
                if (dataResult.getResult().getCode() == 200) {
                    mStates.statistics.set(dataResult.getResult().getData());
                    mAdapter.getCurrentList().get(6).setBadge(dataResult.getResult().getData().getToDoNum());
                    mAdapter.getCurrentList().get(7).setBadge(dataResult.getResult().getData().getWarningNum());
                    mAdapter.getCurrentList().get(8).setBadge(dataResult.getResult().getData().getMsgPushNum());


                    EventMsg eventMsg = new EventMsg();
                    eventMsg.setMsg("badge");
                    eventMsg.setContent(dataResult.getResult().getData().getToDoNum());
                    RxBus.get().post(eventMsg);

                } else {
                    if (401 == dataResult.getResult().getCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        getActivity().finish();
                    }
                    ToastUtils.showLongToast(dataResult.getResult().getMsg());
                }


            } else {
                ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
            }
        });


        RxBus.get().toObservable()
                .map((Function<Object, EventMsg>)
                        o -> (EventMsg) o)
                .subscribe((Consumer<EventMsg>) eventMsg -> {
                    if (eventMsg != null) {

                        if ("warning".equals(eventMsg.getMsg())) {
                            mAccountRequester.getStatistics(UserInfo.getInstance().getProjectCode());
                        }
                    }
                });


        /**
         * 获取考勤打卡详情
         */
        mAccountRequester.sameDayClockInDetail(UserInfo.getInstance().getProjectCode());


        mAccountRequester.getClockInResult().observe(getViewLifecycleOwner(), dataResult -> {

            if (dataResult.getResponseStatus().isSuccess()) {

                if (200 == dataResult.getResult().getCode()) {
                    double distanceClock =
                            Utils.calculateDistance(Double.parseDouble(SPUtil.get(SpKey.KEY_LATITUDE, "0.0", getActivity())),
                                    Double.parseDouble(SPUtil.get(SpKey.KEY_LONGITUDE, "0.0", getActivity())),
                                    Double.parseDouble(UserInfo.getInstance().getProjectLat()),
                                    Double.parseDouble(UserInfo.getInstance().getProjectLon()));

                    dataResult.getResult().getData().setDistanceClock(distanceClock);

                    mAdapter.getCurrentList().get(9).setBadgeClock(dataResult.getResult().getData().getLabel());
                    mAdapter.notifyItemChanged(9);
                    if (showDialog) {
                        if (null == dialog) {
                            dialog = new Dialog(getActivity(), R.style.dialogstyle);
                            View view = View.inflate(getActivity(), R.layout.dialog_home_user_sign, null);

                            binding = DataBindingUtil.bind(view);
                            binding.setClickDialog(new DialogClickProxy());
                            binding.setVm(mStates);
                            dialog.setContentView(view);
                            Window window = dialog.getWindow();
                            window.setBackgroundDrawableResource(android.R.color.transparent);
                            WindowManager.LayoutParams lp = window.getAttributes();
                            lp.width = getResources().getDisplayMetrics().widthPixels;
                            window.setAttributes(lp);
                            window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                        }
                        binding.setVmInfo(dataResult.getResult().getData());
                        dialog.show();
                        showDialog = false;
                    }


                } else {
                    if (401 == dataResult.getResult().getCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        getActivity().finish();
                    }
                    ToastUtils.showLongToast(dataResult.getResult().getMsg());
                }
            } else {
                ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
            }
        });


        mAccountRequester.getWorkOrder().observe(getViewLifecycleOwner(), result -> {

            if (result.getResponseStatus().isSuccess()) {
                if (result.getResult().getResponseCode() == 200) {
                    if (null != result.getResult().getData()) {
                        if (result.getResult().getData().size() > 0) {

                            Intent intent;
                            if (1 == result.getResult().getData().get(0).getIsResponsibleBy()) {
                                intent = new Intent(getActivity(), WorkOrderExamineAlreadyActivity.class);
                            } else {
                                if (0 == result.getResult().getData().get(0).getIsComplete())
                                    intent = new Intent(getActivity(), ManagerWorkOrderDetailsActivity.class);
                                else
                                    intent = new Intent(getActivity(), WorkOrderAlreadyActivity.class);
                            }
                            intent.putExtra("title", patrolType.equals(JCJC) ? "经常检查" : "大坝巡查");
                            intent.putExtra("orderCode", result.getResult().getData().get(0).getOrderCode());
                            intent.putExtra("workOrderSource", result.getResult().getData().get(0).getWorkOrderSource());
                            intent.putExtra("isResponsibleBy", result.getResult().getData().get(0).getIsResponsibleBy());

                            startActivity(intent);
                        } else {
                            ToastUtils.showLongToast("无巡查任务");
                        }
                    } else {
                        ToastUtils.showLongToast("无巡查任务");
                    }
                } else {
                    ToastUtils.showLongToast("无巡查任务");
                }
            } else {
                ToastUtils.showLongToast("无巡查任务");
            }

        });

        mAccountRequester.queryWeatherForecast();
        mAccountRequester.getWeatherDetailBean().observe(this, new Observer<ResponseStatus<WeatherDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<WeatherDetailBean> weatherDetailBeanResponseStatus) {

                if (weatherDetailBeanResponseStatus.getResponseCode() == 200) {

                    WeatherDetailBean.DataBeanX.DataBean.ForecastBean forecastBean = weatherDetailBeanResponseStatus.getData().getData().getData().getForecast().get(weatherDetailBeanResponseStatus.getData().getData().getData().getForecast().size() - 1);
                    mStates.weatherTitle.set(forecastBean.getType() + forecastBean.getLow() + " ~ " + forecastBean.getHigh() + "  I  " + forecastBean.getFx() + forecastBean.getFl());
                    mStates.weatherIcont.set(getItemIcon(forecastBean.getType()));

                } else {
                    mStates.weatherTitle.set("晴26℃  I  东南风2级");
                }

            }
        });


        mBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                HomeFragment.this.onRefresh();
            }
        });

        mAccountRequester.getUserResultProject().observe(this, new Observer<ResponseStatus<UserInfo>>() {
            @Override
            public void onChanged(ResponseStatus<UserInfo> userInfoResponseStatus) {
                if (userInfoResponseStatus.getResponseCode() == 200) {

                    UserInfo.getInstance().setDeptName(userInfoResponseStatus.getData().getAdmin().getDeptName());
                    userInfo = userInfoResponseStatus.getData();
                }
            }
        });
    }

    public UserInfo userInfo;

    private void onRefresh() {

        /**
         * 获取考勤打卡详情
         */
        mAccountRequester.sameDayClockInDetail(UserInfo.getInstance().getProjectCode());
        mAccountRequester.getStatistics(UserInfo.getInstance().getProjectCode());
        mAccountRequester.reservoirInfo(UserInfo.getInstance().getProjectCode());

    }

    public Drawable getItemIcon(String type) {
        switch (type) {
            case "暴雪":
                return getActivity().getResources().getDrawable(R.drawable.baoxue);
            case "暴雨":
                return getActivity().getResources().getDrawable(R.drawable.baoyu);
            case "大暴雨":
                return getActivity().getResources().getDrawable(R.drawable.dabaoyu);
            case "大雪":
                return getActivity().getResources().getDrawable(R.drawable.daxue);
            case "大雨":
                return getActivity().getResources().getDrawable(R.drawable.dayu);
            case "冻雨":
                return getActivity().getResources().getDrawable(R.drawable.dongyu);
            case "多云":
                return getActivity().getResources().getDrawable(R.drawable.duoyun);
            case "浮沉":
                return getActivity().getResources().getDrawable(R.drawable.fuchen);
            case "雷阵雨":
                return getActivity().getResources().getDrawable(R.drawable.leizhenyu);
            case "雷阵雨伴有冰雹":
                return getActivity().getResources().getDrawable(R.drawable.lzybybb);
            case "霾":
                return getActivity().getResources().getDrawable(R.drawable.mai);
            case "强沙尘暴":
                return getActivity().getResources().getDrawable(R.drawable.qiangshachenbao);
            case "晴":
                return getActivity().getResources().getDrawable(R.drawable.qing);
            case "沙暴":
                return getActivity().getResources().getDrawable(R.drawable.shabao);
            case "沙尘暴":
                return getActivity().getResources().getDrawable(R.drawable.shachenbao);
            case "特大暴雨":
                return getActivity().getResources().getDrawable(R.drawable.tedabaoyu);
            case "雾":
                return getActivity().getResources().getDrawable(R.drawable.wu);
            case "小雪":
                return getActivity().getResources().getDrawable(R.drawable.xiaoxue);
            case "小雨":
                return getActivity().getResources().getDrawable(R.drawable.xiaoyu);
            case "阴":
                return getActivity().getResources().getDrawable(R.drawable.yin);
            case "雨夹雪":
                return getActivity().getResources().getDrawable(R.drawable.yujiaxue);
            case "阵雪":
                return getActivity().getResources().getDrawable(R.drawable.zhenxue);
            case "阵雨":
                return getActivity().getResources().getDrawable(R.drawable.zhenyu);
            case "中雪":
                return getActivity().getResources().getDrawable(R.drawable.zhongxue);
            case "中雨":
                return getActivity().getResources().getDrawable(R.drawable.zhongyu);
            default:
                return getActivity().getResources().getDrawable(R.drawable.qing);
        }
    }


    /**
     * 是否显示签到弹窗
     */
    private boolean showDialog;

    public static class HomeFragmentStates extends StateHolder {

        public final State<String> name = new State<>(UserInfo.getInstance().getName());

        public final State<List<LibraryInfo>> list = new State<>(new ArrayList<>());
        public final State<List<LibraryInfo>> listGate = new State<>(new ArrayList<>());
        public final State<List<LibraryInfo>> listGateTitle = new State<>(new ArrayList<>());
        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<ClockInBean.DataBean> statistics = new State<>(null);
        public final State<String> weatherTitle = new State<>("");
        public final State<Drawable> weatherIcont = new State<>(null);


    }

    private Dialog dialog;

    private PopupWindow popupWindow;
    LayoutSpinnerPopupBinding spinnerPopupBinding;

    public class ClickProxy {
        /**
         * 切换水库
         */
        public void wayProject() {

            if (null == userInfo)
                return;
            if (null == popupWindow) {
                popupWindow = new PopupWindow(getActivity());
                View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_spinner_popup, null);

                spinnerPopupBinding = DataBindingUtil.bind(popupView);
                // 创建PopupWindow实例
                popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                // 设置PopupWindow可以获得焦点，否则无法响应点击事件
                popupWindow.setFocusable(true);
                SimpleDataBindingPositionAdapter<UserInfo.ProjectListBean, ItemTextBinding>
                        popupAdapter = new SimpleDataBindingPositionAdapter<UserInfo.ProjectListBean, ItemTextBinding>
                        (getActivity(), R.layout.item_text,
                                new DiffUtil.ItemCallback<UserInfo.ProjectListBean>() {
                                    @Override
                                    public boolean areItemsTheSame(@NonNull UserInfo.ProjectListBean oldItem,
                                                                   @NonNull UserInfo.ProjectListBean newItem) {
                                        return false;
                                    }

                                    @Override
                                    public boolean areContentsTheSame(@NonNull UserInfo.ProjectListBean oldItem,
                                                                      @NonNull UserInfo.ProjectListBean newItem) {
                                        return false;
                                    }
                                }) {
                    @Override
                    protected void onBindItem(ItemTextBinding binding, UserInfo.ProjectListBean item,
                                              ViewHolder holder, int position) {
                        binding.setVm(item);
                    }
                };


                List<UserInfo.ProjectListBean> list = new ArrayList<>();
                for (UserInfo.ProjectListBean projectListBean : userInfo.getProjectList()) {
                    if (1 == projectListBean.getIsExperiment()) {
                        list.add(projectListBean);
                    }
                }
                popupAdapter.submitList(list);
                spinnerPopupBinding.setAdapter(popupAdapter);
                popupAdapter.setOnItemClickListener((viewId, item, position) -> {

                    mStates.projectName.set(item.getProjectName());
                    UserInfo.getInstance().setProjectCode(item.getProjectCode());
                    UserInfo.getInstance().setProjectName(item.getProjectName());
                    mStates.appLog.set(item.getPictureUrlSrc());
                    onRefresh();
                    popupWindow.dismiss();

                    EventMsg eventMsg = new EventMsg();
                    eventMsg.setMsg("warning");
                    RxBus.get().post(eventMsg);
                    EventBus.getDefault().post(eventMsg);
                });
            }

            // 显示下拉弹窗
            popupWindow.showAsDropDown(mBinding.tvNsgfHomeProject, 0, 0);


        }
    }

    public class DialogClickProxy {

        public void cancel() {
            dialog.dismiss();
        }

        public void clockIn() {
            double distanceClock =
                    Utils.calculateDistance(Double.parseDouble(SPUtil.get(SpKey.KEY_LATITUDE, "0.0", getActivity())),
                            Double.parseDouble(SPUtil.get(SpKey.KEY_LONGITUDE, "0.0", getActivity())),
                            Double.parseDouble(UserInfo.getInstance().getProjectLat()),
                            Double.parseDouble(UserInfo.getInstance().getProjectLon()));

            if (distanceClock > binding.getVmInfo().getDistance()) {
                ToastUtils.showLongToast("您未进入有效打卡范围");
                return;
            }
            mAccountRequester.punchTheClock(UserInfo.getInstance().getProjectCode());
        }

        public void more() {
            startActivity(new Intent().setClass(getActivity(), CheckWorkAttendanceDetailsActivity.class));
            dialog.dismiss();
        }

        public void refresh() {

            startLocation(false);

        }
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        super.onLocationChanged(location);

        double distanceClock =
                Utils.calculateDistance(Double.parseDouble(SPUtil.get(SpKey.KEY_LATITUDE, "0.0", getActivity())),
                        Double.parseDouble(SPUtil.get(SpKey.KEY_LONGITUDE, "0.0", getActivity())),
                        Double.parseDouble(UserInfo.getInstance().getProjectLat()),
                        Double.parseDouble(UserInfo.getInstance().getProjectLon()));

        if (null != binding)
            binding.getVmInfo().setDistanceClock(distanceClock);
        if (distanceClock > binding.getVmInfo().getDistance()) {
            ToastUtils.showLongToast("您未进入有效打卡范围");
        }
    }
}
